﻿using System;
using System.Linq;
using System.Web.Services;
using Dost.Khcn.Biz;
using Dost.Khcn.Web.Common;

namespace Dost.Khcn.Web.DanhMuc.TinhThanhPho
{
    public class List : System.Web.UI.Page
    {
        #region Properites
        
        private static TinhThanhPhoBiz _tinhThanhPhoBiz;
        private static TinhThanhPhoBiz TinhThanhPhoManager
        {
            get { return _tinhThanhPhoBiz ?? (_tinhThanhPhoBiz = new TinhThanhPhoBiz()); }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            //if (WebCommon.CurrrentEmployee == null)
            //{
            //    Response.Redirect("~/Logon.aspx");
            //    return;
            //}

            if (!WebCommon.CurrrentEmployee.IsAdmin)
            {
                Response.Redirect("~/NoPermission.aspx");
            }
        }

        #region Web methods
        
        [WebMethod(EnableSession = true)]
        public static object TinhThanhPhoList(int jtStartIndex, int jtPageSize, string jtSorting, string name)
        {
            return TinhThanhPhoManager.GetTinhThanhPhos(jtStartIndex, jtPageSize, jtSorting, name);
        }

        [WebMethod(EnableSession = true)]
        public static object Delete(int Id)
        {
            return TinhThanhPhoManager.DeleteTinhThanhPho(Id);
        }

        [WebMethod(EnableSession = true)]
        public static object Create(Data.EntityModel.TinhThanhPho record)
        {
            try
            {
                var addedRecord = TinhThanhPhoManager.CreateTinhThanhPho(record);
                return new { Result = "OK", Record = addedRecord };
            }
            catch (ApplicationException appEx)
            {
                return new { Result = "ERROR", Message = string.Format(WebCommon.GetGlobalString(appEx.Message), record.Ten) };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object Update(Data.EntityModel.TinhThanhPho record)
        {
            try
            {
                TinhThanhPhoManager.UpdateTinhThanhPho(record);
                return new { Result = "OK" };
            }
            catch (ApplicationException appEx)
            {
                return new { Result = "ERROR", Message = string.Format(WebCommon.GetGlobalString(appEx.Message), record.Ten) };
            }
        }

        [WebMethod(EnableSession = true)]
        public static object GetOptions()
        {
            var tinhThanhPhos = TinhThanhPhoManager.GetAllTinhThanhPhos();
            tinhThanhPhos.Insert(0, new Data.EntityModel.TinhThanhPho { Id = 0, Ten = string.Empty });

            return new { Result = "OK", Options = tinhThanhPhos.Select(x => new { DisplayText = x.Ten, Value = x.Id }) };
        }

        #endregion
    }
}